package com.cxq;

import com.sun.xml.internal.bind.v2.model.annotation.RuntimeAnnotationReader;

import java.util.concurrent.Semaphore;

/**
 * Created by cxq on 2020/7/26.
 */
public class WorkerMachine {

    //内部类
    static class Work implements Runnable{
        private  int workNo;//工人的工号
        private Semaphore semaphore;//机器数

        public Work(int workNo, Semaphore semaphore) {
            this.workNo = workNo;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            //工人要去获取机器
            try {
                semaphore.acquire();
                //打印工人获取到机器，开始工作
                System.out.println(Thread.currentThread().getName()+"获取到机器，开始工作");
                //线程睡眠1000毫秒，模拟工人使用机器工作过程
                Thread.sleep(1000);
                //使用完毕，释放机器，打印工人使用完毕，释放机器
                semaphore.release();
                System.out.println(Thread.currentThread().getName()+"工人使用完毕，释放机器！");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        int workers=8;//8个工人
        Semaphore semaphore = new Semaphore(3);//3台机器
        for(int i=0;i<workers;i++){
            new Thread(new Work(i,semaphore)).start();
        }
    }
}
